package cn.vacuumflask.flaskutils.adapter;

import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * DataBinding 通用 Adapter
 *
 * @param <T> 数据实体
 */
public abstract class CommonAdapter<T> extends RecyclerView.Adapter<CommonAdapter.CommonViewHolder> {
    public List<T> data;

    private OnRecycleViewItemClickListener<T> itemClickListener;

    private OnRecycleViewItemLongClickListener<T> longClickListener;

    public CommonAdapter(List<T> data) {
        this.data = data;
    }

    protected abstract CommonViewHolder setViewHolder(ViewGroup viewGroup, int viewType);

    protected abstract void setBindViewHolder(CommonViewHolder viewHolder, int position);

    @NonNull
    @Override
    public CommonViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return setViewHolder(viewGroup, i);
    }

    @Override
    public void onBindViewHolder(@NonNull CommonViewHolder commonViewHolder, int i) {
        setBindViewHolder(commonViewHolder, i);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void setItemClickListener(OnRecycleViewItemClickListener<T> itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public void setLongClickListener(OnRecycleViewItemLongClickListener<T> longClickListener) {
        this.longClickListener = longClickListener;
    }

    public class CommonViewHolder<D extends ViewDataBinding> extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        public D binding;

        public CommonViewHolder(@NonNull View itemView, D binding) {
            super(itemView);
            this.binding = binding;
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
        }

        @Override
        public void onClick(View v) {

            if (itemClickListener != null) {
                int position = getAdapterPosition();
                if (data.size() > position && position >= 0) {
                    T item = data.get(position);
                    itemClickListener.onRecycleViewItemClickListener(itemView, item, position);
                }
            }

        }

        @Override
        public boolean onLongClick(View v) {

            if (longClickListener != null) {
                int position = getAdapterPosition();
                if (data.size() > position && position >= 0) {
                    T item = data.get(position);
                    return longClickListener.onRecycleViewItemLongClickListener(itemView, item, position);
                }
            }

            return false;
        }
    }
}
